<template>
	<view class="main">
		<u-sticky>
			<subAccountQualificationAddStep :step="2" />
		</u-sticky>

		<view class="content">
			<u--form labelPosition="left" :model="merchantDetail" :rules="syntheticalInfoModelRules"
				ref="syntheticalInfoForm" labelWidth="87"
				:labelStyle="{fontSize:'26rpx', color: 'rgba(0, 0, 0, 0.7)', padding: '18rpx 0'}">
				<view class="content-item" v-if="merchantDetail.merchantType == merchantTypeEnum.INDIVIDUAL_HOUSEHOLD.id
						|| merchantDetail.merchantType == merchantTypeEnum.LIMITED_COMPANY.id">
					<view class="content-title">上传经营信息</view>

					<u-form-item label=" " prop="licenseAndIndustryLicensePhotoUpLoaded"
						ref="licenseAndIndustryLicenseItem" labelWidth="0"
						v-if="merchantDetail.merchantType != merchantTypeEnum.PERSON.id">
						<view class="upload u-flex u-row-between">
							<u-upload ref="licensePhotoUpload" :fileList="licensePhotoUrlList"
								@afterRead="photoUploadAfterRead" :name="photoTypeEnum.licensePhoto" :maxCount="1"
								:width="imgWidth" :height="imgHeight" :maxSize="maxSize" @oversize="bannerOversize"
								@delete="deletePhoto(photoTypeEnum.licensePhoto)">
								<u--image :showLoading="true"
									:src="`${baseStaticFileUrl}/image/pages-qualification/license-photo.png`"
									:width="imgWidth" :height="imgHeight" />
							</u-upload>

							<u-upload :fileList="industryLicensePhotoUrlList" @afterRead="photoUploadAfterRead"
								:name="photoTypeEnum.industryLicensePhoto" :maxCount="1" :width="imgWidth"
								:height="imgHeight" :maxSize="maxSize" @oversize="bannerOversize"
								@delete="deletePhoto(photoTypeEnum.industryLicensePhoto)"
								v-if="merchantDetail.merchantType == merchantTypeEnum.LIMITED_COMPANY.id">
								<u--image :showLoading="true"
									:src="`${baseStaticFileUrl}/image/pages-qualification/industry-license-photo.png`"
									:width="imgWidth" :height="imgHeight" />
							</u-upload>

						</view>
					</u-form-item>

					<u-form-item label="营业执照名称" prop="legalPerson" borderBottom ref="legalPersonItem"
						v-if="merchantDetail.merchantType != merchantTypeEnum.PERSON.id">
						<u--input border="none" placeholder="请输入营业执照名称" inputAlign="left" clearable fontSize="13"
							maxlength="64" v-model="merchantDetail.legalPerson" />
					</u-form-item>
					<u-form-item label="统一社会信用代码" prop="bussAuthNum" borderBottom ref="bussAuthNumItem"
						v-if="merchantDetail.merchantType != merchantTypeEnum.PERSON.id">
						<u--input border="none" type="text" placeholder="请输入统一社会信用代码" inputAlign="left" clearable
							fontSize="13" maxlength="18" v-model="merchantDetail.bussAuthNum" />
					</u-form-item>

				</view>

			</u--form>
		</view>

		<view class="footer">
			<u-button type="primary" text="提交" :customStyle="nextStepBtnCustomStyle" @click="submit()" />
		</view>

		<licensePhotoComponent ref="licensePhotoComponent" />

		<storeInfoComponent ref="storeInfoComponent" />
	</view>
</template>

<script>
	import licensePhotoComponent from '@/pages-qualification/base-info/license-photo';
	import storeInfoComponent from '@/components/store-info/store-info';
	import merchantDetail from '@/common/po/merchant-detail.ts'
	import subAccountQualificationAddStep from '@/components/qualification-add-step/sub-account-qualification-add-step';
	export default {
		name: "synthetical-info",
		components: {
			subAccountQualificationAddStep,
			licensePhotoComponent,
			storeInfoComponent
		},
		data() {
			return {
				qiNiuImgURL: this.$configPath.qiNiuImgURL,
				baseStaticFileUrl: this.$configPath.staticFileUrl,

				maxSize: 3 * 1024 * 1024,
				imgWidth: '330rpx',
				imgHeight: '234rpx',
				nextStepBtnCustomStyle: {
					width: '690rpx',
					height: '88rpx',
					borderRadius: '120px',
					color: '#fff',
					margin: '14rpx auto 0rpx',
				},

				merchantDetail: merchantDetail,
				syntheticalInfoModelRules: {},

				licensePhotoUrlList: [],
				industryLicensePhotoUrlList: [],

				photoTypeEnum: {
					licensePhoto: 'licensePhoto',
					industryLicensePhoto: 'industryLicensePhoto',
				},
				merchantTypeEnum: this.$merchantTypeEnum,
				merchantInfoUploadStateEnum: this.$merchantInfoUploadStateEnum,
			}
		},
		onReady() {
			this.$refs.syntheticalInfoForm.setRules(this.syntheticalInfoModelRules)
		},
		onLoad() {
			this.getUncommittedMerchantInfo();
		},
		onUnload() {
			uni.$emit('updateMerchantInfo-syntheticalInfo', {
				data: this.merchantDetail
			})
		},
		methods: {
			initData(data) {
				this.merchantDetail = data;
				// console.log("this.merchantDetail", this.merchantDetail)

				if (this.merchantDetail.merchantType != this.merchantTypeEnum.PERSON.id) {
					this.syntheticalInfoModelRules['licenseAndIndustryLicensePhotoUpLoaded'] = {
						type: 'boolean',
						required: true,
						message: '请上传营业执照、开户许可证照片',
						validator: (rule, value, callback) => {
							return value == true;
						},
					};
					this.syntheticalInfoModelRules['legalPerson'] = {
						type: 'string',
						required: true,
						message: '请输入营业执照名称',
						max: 64,
						min: 3,
						trigger: ['blur'],
					};
					this.syntheticalInfoModelRules['bussAuthNum'] = {
						type: 'string',
						required: true,
						message: '请输入统一社会信用代码，由18位数字、字母组成',
						len: 18,
						trigger: ['blur'],
					};
				}

				// 营业执照
				if (!this.$u.test.isEmpty(this.merchantDetail.licensePhoto)) {
					this.licensePhotoUrlList.length = 0;
					this.licensePhotoUrlList.push({
						status: 'success',
						message: '',
						url: this.qiNiuImgURL + getApp().formatImageSuffix(this.merchantDetail.licensePhoto)
					})
				}

				// 开户许可证
				if (!this.$u.test.isEmpty(this.merchantDetail.industryLicensePhoto)) {
					this.industryLicensePhotoUrlList.length = 0;
					this.industryLicensePhotoUrlList.push({
						status: 'success',
						message: '',
						url: this.qiNiuImgURL + getApp().formatImageSuffix(this.merchantDetail
							.industryLicensePhoto)
					})
				}

				this.checkLicensePhotoAndIndustryLicensePhoto();
			},

			async photoUploadAfterRead(event) {
				uni.showLoading({
					title: '上传中',
					mask: true
				})

				// #ifndef H5
				let _this = this;
				if(event.file.size > 1024000){
					uni.compressImage({
						src: event.file.url,
						quality: 60,
						success: comRes => {
							_this.photoUploadAfterReadFun(event,comRes.tempFilePath);
						}
					})
				}else{
					this.photoUploadAfterReadFun(event,event.file.url);
				}
				// #endif
				
				// #ifdef H5
				this.photoUploadAfterReadFun(event,event.file.url);
				// #endif
			},
			
			async photoUploadAfterReadFun(event,fileUrl) {
				const item = {
					url: fileUrl,
					status: 'uploading',
					message: '上传中'
				}
				if (event.name == this.photoTypeEnum.licensePhoto) {
					this.licensePhotoUrlList.push(item);

					await this.photoUploadFilePromise(fileUrl, this.$photoTypeEnum.LICENSE_PHOTO).then((
						res) => {
						this.merchantDetail.licensePhoto = res.data.picture;
						this.merchantDetail.legalPerson = res.data.legalPerson;
						this.merchantDetail.bussAuthNum = res.data.bussAuthNum;
						// this.merchantDetail.address = res.data.address;

						const url = this.qiNiuImgURL + getApp().formatImageSuffix(res.data.picture);
						this.licensePhotoUrlList.splice(0, 1, Object.assign(item, {
							status: 'success',
							message: '',
							url: url
						}))

						this.checkLicensePhotoAndIndustryLicensePhoto(true);

						// 上传成功，识别失败
						if (this.merchantInfoUploadStateEnum.FAILURE_TO_IDENTIFY == res.status) {
							// 调起识别失败提示，并将刚上传的图片展示给他看
							this.$refs.licensePhotoComponent.showPopup(url);
						}

					}).catch((err) => {
						this.licensePhotoUrlList.splice(0, 1);
					})
				} else if (event.name == this.photoTypeEnum.industryLicensePhoto) {
					this.industryLicensePhotoUrlList.push(item);

					await this.photoUploadFilePromise(fileUrl, null).then((res) => {
						this.merchantDetail.industryLicensePhoto = res.data.picture;

						const url = this.qiNiuImgURL + getApp().formatImageSuffix(res.data.picture);
						this.industryLicensePhotoUrlList.splice(0, 1, Object.assign(item, {
							status: 'success',
							message: '',
							url: url
						}))

						this.checkLicensePhotoAndIndustryLicensePhoto(true);
					}).catch((err) => {
						this.industryLicensePhotoUrlList.splice(0, 1);
					})
				} else {
					uni.hideLoading();
					this.$helpers.toast("e.name有误");
					return
				}
				
			},

			photoUploadFilePromise(fileUrl, photoType) {
				// console.log("photoType", photoType)
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: this.$configPath.baseURL + '/api/merchant/merchantRegisterUploadByApplet',
						filePath: fileUrl,
						name: 'file',
						header: {
							Authorization: 'Bearer ' + this.$store.getters.GET_VALUE("GET_TOKEN")
						},
						timeout: 6000,
						formData: {
							photoType: photoType
						},
						success: (res) => {
							uni.hideLoading();
							let data = JSON.parse(res.data);
							if (this.merchantInfoUploadStateEnum.SUCCESS == data.status) {
								this.$helpers.toast("上传成功", "success");
								resolve(data);
							} else if (this.merchantInfoUploadStateEnum.FAILURE_TO_IDENTIFY == data
								.status) {
								//上传成功，识别失败
								resolve(data);
							} else {
								reject(data)
								getApp().err("上传不成功，" + data.msg);
							}
						},
						fail: (res) => {
							uni.hideLoading();
							let errMsg = res.errMsg;
							if (uni.$u.test.contains(errMsg, 'timeout')) {
								errMsg = "请求超时，请重新上传";
							}
							getApp().err(errMsg);
							reject("请求超时，请重新上传")
						},
					});
				})
			},

			bannerOversize() {
				getApp().err("图片大小超限，最大3MB。如图片来自相册，建议使用直接拍摄");
			},

			deletePhoto(photoType) {
				try {
					if (photoType == this.photoTypeEnum.licensePhoto) {
						this.merchantDetail.licensePhoto = "";
						this.merchantDetail.legalPerson = "";
						this.merchantDetail.bussAuthNum = "";
						this.licensePhotoUrlList.splice(0, 1)
					} else if (photoType == this.photoTypeEnum.industryLicensePhoto) {
						this.merchantDetail.industryLicensePhoto = "";
						this.industryLicensePhotoUrlList.splice(0, 1)
					} else {
						getApp().err("图片类型有误")
					}
					this.checkLicensePhotoAndIndustryLicensePhoto(true);
				} catch (e) {
					console.error(e.toString())
					this.$helpers.toast("删除不成功");
				}
			},

			// 检查许可证照片和行业许可证照片
			checkLicensePhotoAndIndustryLicensePhoto(checked) {
				if (this.merchantDetail.merchantType == this.merchantTypeEnum.INDIVIDUAL_HOUSEHOLD.id) {
					// 个体户资质时就判断营业执照即可
					if (!this.$u.test.isEmpty(this.merchantDetail.licensePhoto)) {
						this.merchantDetail.licenseAndIndustryLicensePhotoUpLoaded = true;
					} else {
						this.merchantDetail.licenseAndIndustryLicensePhotoUpLoaded = false;
					}
				} else {
					// 公司资质对个人、对公
					if (!this.$u.test.isEmpty(this.merchantDetail.licensePhoto) &&
						!this.$u.test.isEmpty(this.merchantDetail.industryLicensePhoto)
					) {
						this.merchantDetail.licenseAndIndustryLicensePhotoUpLoaded = true;
					} else {
						this.merchantDetail.licenseAndIndustryLicensePhotoUpLoaded = false;
					}
				}

				if (checked) {
					this.licenseAndIndustryLicensePhotoValidateField();
					this.legalPersonValidateField();
					this.bussAuthNumValidateField();
				}
			},

			licenseAndIndustryLicensePhotoValidateField() {
				this.$refs.syntheticalInfoForm.validateField('licenseAndIndustryLicensePhotoUpLoaded', err => {
					// console.log("err", err)
				})
			},

			legalPersonValidateField() {
				this.$refs.syntheticalInfoForm.validateField('legalPerson', err => {
					// console.log("err", err)
				})
			},

			bussAuthNumValidateField() {
				this.$refs.syntheticalInfoForm.validateField('bussAuthNum', err => {
					// console.log("err", err)
				})
			},

			// 打开上传示例
			openUploadDemo(photoType) {
				this.$refs.syntheticalInfoComponent.showPopup(photoType);
			},

			// 营业执照重新上传
			licensePhotoUploadAgain() {
				this.licensePhotoUrlList.splice(0, 1);
				this.$nextTick(() => {
					this.$refs.licensePhotoUpload.chooseFile()
				})
			},

			// 获取最近一次的记录
			getUncommittedMerchantInfo() {
				this.$api('merchant.getUncommittedSubAccountMerchantInfo', null).then(res => {
					if (res.status == 0) {
						if (!this.$u.test.isEmpty(res.data)) {
							this.initData(res.data);
						}
					}
				}).catch(() => {
					uni.hideLoading();
				})
			},

			// 更新记录
			updateUncommittedMerchantInfo() {
				this.$api('merchant.updateUncommittedSubAccountMerchantInfo', this.merchantDetail).then(res => {
					uni.hideLoading();
				}).catch(() => {
					uni.hideLoading();
				})
			},

			submit() {
				try {
					let rules = Object.keys(this.syntheticalInfoModelRules)
					if (rules.length > 0) {
						this.$refs.syntheticalInfoForm.validate().then(res => {
							uni.showLoading();
							this.updateUncommittedMerchantInfo()
							this.subLedgerMerchantRegisterByApplet();
						}).catch(errors => {
							getApp().err('请按红色文字提示输入完整信息才能进行下一步')
						})
					} else {
						this.subLedgerMerchantRegisterByApplet();
					}
				} catch (e) {
					console.error(e.toString())
					getApp().err('提交不成功：' + e.toString())
				}
			},

			subLedgerMerchantRegisterByApplet() {
				uni.showLoading({
					title: '加载中...',
					mask: true
				})
				this.$api('merchant.subLedgerMerchantRegisterByApplet', this.merchantDetail).then(res => {
					if (res.status == 0) {
						this.$helpers.toast('提交成功，请耐心等待审核', 'none', 4000, true, () => {
							uni.switchTab({
								url: '/pages/home/home',
								success() {
									uni.navigateTo({
										url: '/pages-automatic-ledger/automatic-ledger/ledger-account'
									})
								}
							})
						});
					} else {
						uni.hideLoading();
						getApp().err("提交不成功，" + res.msg);
					}
				}).catch((err) => {
					uni.hideLoading();
					getApp().err('提交不成功，' + err)
				})
			},
		}
	}
</script>

<style lang="scss" scoped>
	.main {
		.content {
			.content-item {
				background-color: $uni-bg-color;
				margin-bottom: 20rpx;
				padding: 24rpx 30rpx;

				.content-title {
					color: rgb(13, 13, 13);
					font-size: 30rpx;
				}

				.upload {
					padding: 30rpx 0rpx 12rpx;
				}
			}
		}

		.footer {
			width: 100%;
			margin-top: 94rpx;
			padding-bottom: 74rpx;
		}
	}

	/deep/ .u-upload__wrap__preview {
		margin: 0 8px 0px 0 !important;
	}

	/deep/ .u-textarea__field {
		color: #303133 !important;
		font-size: $f-sm !important;
	}
</style>
